<template>
    <div class="master-sub-page">
      <!-- 查询表单 -->
      <ele-form-search
        :formConfig="searchDialog"
        @handleSearch="handleSearch"
        @handleReset="handleReset"
        ref="eleFormSearch"
      ></ele-form-search>
      <div class="tableLayout">
        <div class="leftTable">
          <ele-table
            v-loading="loading"
            ref="eleTable"
            v-on="$listeners"
            :column="column"
            :beforeRequest="selfMasterBeforeRequest"
            :operateList="operateList"
            @handleOperateEvent="handleOperateEvent"
            :getList="mesTmMaterialBasePage"
            uniqueId="mesTmMaterialBaseTable"
            @row-click="masterRowClick"
          ></ele-table>
        </div>
        <div class="rightTable" >
          <el-tabs v-model="activeName" type="border-card" >
            <el-tab-pane label="品牌" name="1">
              <!-- 出库任务 -->
              <div class="sub-form-search">
                <ele-form-search
                  ref="eleDetailFormSearch"
                  :formConfig="detailSearchConfig"
                  @handleSearch="handleDetailSearch"
                  @handleReset="handleDetailReset"
                ></ele-form-search>
              </div>
              <!-- 子列表展示 -->
              <div ref="tableTop">
                <ele-table
                  ref="domDetailTable"
                  :column="detailColumn"
                  :apiImmediate="false"
                  :getList="mesTmMaterialBrandPage"
                  :beforeRequest="selfSubBeforeRequest"
                  :operateList="operateList"
                  @handleOperateEvent="handleSubOperateEvent"
                >
                </ele-table>
              </div>
            </el-tab-pane>
            <el-tab-pane label="规格" name="2">
              <div>
                <ele-table
                  ref="domDetailTableUnit"
                  :column="detailUnitColumn"
                  :apiImmediate="false"
                  :getList="mesTmMaterialUnitPage"
                  :beforeRequest="selfSubBeforeRequest"
                  :operateList="operateList"
                  @handleOperateEvent="handleSubOperateEventUnit"
                >
                </ele-table>
              </div>
              <!-- 出库明细 -->
            </el-tab-pane>
          </el-tabs>


        </div>

      </div>
      <ele-form-drawer class="dialog-pack"
        ref="masterDrawer"
        :isLoading="isLoading"
        v-model="formDataDialog"
        v-bind="formDescDialog"
        :request-fn="handleSubmit"
        :visible.sync="visible"
        :title="title"
      >
      </ele-form-drawer>

      <ele-form-drawer class="dialog-pack"
        ref="subDrawer"
        :isLoading="isSubLoading"
        v-model="subFormDataDialog"
        v-bind="subFormDescDialog"
        :request-fn="subHandleSubmit"
        :visible.sync="subVisible"
        :title="title"
        @input="handleInput"
      >
      </ele-form-drawer>
      <ele-form-drawer class="dialog-pack"
                       ref="subDrawerUnit"
                       :isLoading="isSubLoading"
                       v-model="subUnitFormDataDialog"
                       v-bind="subUnitFormDescDialog"
                       :request-fn="subHandleSubmitUnit"
                       :visible.sync="subUnitVisible"
                       :title="title"
                       @input="handleInputUnit"
      >
      </ele-form-drawer>
      <!-- 此组件放到与抽屉平级，理论上不需要修改 -->
    </div>
  </template>

  <script>
  import eleFormSearch from "@/components/ele-form-search";
  import { operateList, searchConfig, formDescDialogMixin,subUnitFormDescDialogMixin, subFormDescDialogMixin, rowConfig, detailSearchConfig } from './config'


  import {mesTmMaterialBaseCreate, mesTmMaterialBaseDeleteById, mesTmMaterialBasePage, mesTmMaterialBaseUpdate} from "@/api/materials/tmMaterialBase";
  import {mesTmMaterialBrandCreate, mesTmMaterialBrandDeleteById, mesTmMaterialBrandPage, mesTmMaterialBrandUpdate} from "@/api/materials/brand";
  import {mesTmMaterialUnitCreate, mesTmMaterialUnitDeleteById, mesTmMaterialUnitPage, mesTmMaterialUnitUpdate} from "@/api/materials/unit";
  import {getDict} from "@/api/common";
  import { searchArrKey } from '@/mixins/searchArrKey'
  import {
    addResizeListener,
    removeResizeListener,
  } from "element-ui/src/utils/resize-event";
  export default {
    name: 'mesTmMaterialBase',
    mixins: [ formDescDialogMixin, subFormDescDialogMixin, subUnitFormDescDialogMixin,searchConfig, searchArrKey, detailSearchConfig],
    components: { eleFormSearch },
    data() {
      const self = this
      return {
        maxHeight: 1,
        title: null,
        visible: false,
        subVisible: false,
        subUnitVisible: false,
        isLoading: false,
        isSubLoading: false,
        loading: false,
        activeName: "1",
        formDataDialog: {},
        subFormDataDialog: {},
        subUnitFormDataDialog: {},
        // formDescDialog, //新增修改框
        operateList,
        mesTmMaterialBasePage,
        mesTmMaterialBrandPage,
        mesTmMaterialUnitPage,
        // 列表页字段的绑定配置
        column: [
          {
            type: 'selection',
            fixed: 'left'
          },
          {
            type: 'index',
            label: $i18n.t('common.order'),
            width: 60,
            fixed: 'left'
          },
          {
            prop: "materialType",
            label: '类型',
            optionProp: {
              value: "value",
              label: "description",
            },
            option: async (data) => {
              const list = await getDict("tm_material_base")
              return list.data.result;
            },
            showOverflowTooltip: true,
          },
          {
            prop: 'materialCode',
            label: '物料编号',
            showOverflowTooltip: true
          },
          {
            prop: 'materialName',
            label: '物料名称',
            showOverflowTooltip: true
          },
          {
            prop: "materialUnit",
            label: '物料单位',
            optionProp: {
              value: "value",
              label: "description",
            },
            option: async (data) => {
              const list = await getDict("material_unit")
              return list.data.result;
            },
            showOverflowTooltip: true,
          },
          {
            prop: 'operate',
            label: $i18n.t('common.operation'),
            width: 160,
            fixed: 'right',
            render: (h, scope) => {
              return <ele-row-operation scope={scope} rowConfig={rowConfig} onRowOperate={this.rowOperate} />
            }
          }
        ],
        detailColumn: [
          {
            type: 'selection',
            fixed: 'left'
          },
          {
            type: 'index',
            label: $i18n.t('common.order'),
            width: 60,
            fixed: 'left'
          },
          {
            prop: 'materialCode',
            label: '物料编码',
            minWidth: 140,
            showOverflowTooltip: true
          },
          {
            prop: 'brand',
            label: '品牌',
            minWidth: 140,
            showOverflowTooltip: true
          },
          {
            prop: 'createByName',
            label: '创建人',
            minWidth: 140,
            showOverflowTooltip: true
          },
          {
            prop: 'createTime',
            label: '创建时间',
            minWidth: 140,
            showOverflowTooltip: true
          },
          {
            prop: 'operate',
            label: $i18n.t('common.operation'),
            width: 160,
            fixed: 'right',
            render: (h, scope) => {
              return <ele-row-operation scope={scope} rowConfig={rowConfig} onRowOperate={this.subRowOperate} />
            }
          }
        ],
        detailUnitColumn: [
          {
            type: 'selection',
            fixed: 'left'
          },
          {
            type: 'index',
            label: $i18n.t('common.order'),
            width: 60,
            fixed: 'left'
          },
          {
            prop: 'materialCode',
            label: '物料编码',
            minWidth: 140,
            showOverflowTooltip: true
          },
          {
            prop: 'unit',
            label: '规格',
            minWidth: 100,
            showOverflowTooltip: true
          },
          {
            prop: 'packUnit',
            label: '包装单位',
            minWidth: 100,
            showOverflowTooltip: true
          },
          {
            prop: 'packCapacity',
            label: '包装容量',
            minWidth: 100,
            showOverflowTooltip: true
          },
          {
            prop: 'countType',
            label: '统计方式',
            minWidth: 100,
            showOverflowTooltip: true,
            render: (h, scope) => {
              const status = scope.row.countType == '1' ? "基础单位" : "包装单位"
              return <div>{status}</div>
            },
          },
          {
            prop: 'createByName',
            label: '创建人',
            minWidth: 140,
            showOverflowTooltip: true
          },
          {
            prop: 'createTime',
            label: '创建时间',
            minWidth: 140,
            showOverflowTooltip: true
          },
          {
            prop: 'operate',
            label: $i18n.t('common.operation'),
            width: 160,
            fixed: 'right',
            render: (h, scope) => {
              return <ele-row-operation scope={scope} rowConfig={rowConfig} onRowOperate={this.subUnitRowOperate} />
            }
          }
        ],
        rowParams: {
          materialCode: null,
          materialName: null
        },
      }
    },
    computed: {},
    methods: {
      handleInput() {

      },
      handleInputUnit() {

      },
      packUnitChange(val) {
        console.warn(val)
        if(val === '无')
        {
          this.subUnitFormDataDialog.packCapacity = 1;
          this.subUnitFormDataDialog.countType = '1';
        }
      },
      handleSearch() {
        this.tabaleSearch();
      },
      handleReset() {
        this.tabaleSearch();
      },
      //子表搜索
      handleDetailSearch() {
        this.subRefresh(false)
      },
      //子表重置
      handleDetailReset() {
        this.subRefresh()
      },
      // 主表，请求之前操作
      selfMasterBeforeRequest(data) {
        const params = { ...data, ...this.getSearchParams() }
        return params
      },
      // 获取搜索参数
      getSearchParams() {
        let formData = this.$refs.eleFormSearch.formData || {}
        formData = this.getArrtoMap(formData)
        return formData
      },
      tabaleSearch(isReset = true) {
        this.$nextTick(() => {
          this.$refs.eleTable.getTableData(isReset);
        });
      },
      // 表格顶部按钮操作事件
      handleOperateEvent(data) {
        this.title = data.name
        const fnc = {
          add: () => {
            this.visible = true
            this.formDataDialog = {
            }
          },
          deleteBatch: () => {
            this.$confirm('此操作将删除所选数据, 是否继续?', $i18n.t('common.tip'), {
              confirmButtonText: $i18n.t('common.ok'),
              cancelButtonText: $i18n.t('common.cancel'),
              type: 'warning'
            }).then(() => {
              const ids = data.rows.map((val) => val.id).join(',')
              this.rowDel(ids)
            })
          },
        }
        fnc[data.handleName]()
      },
      // 子表顶部按钮操作事件
      handleSubOperateEvent(data) {
        this.title = data.name
        const fnc = {
          add: () => {
            if(this.rowParams.materialCode)
            {
              this.subVisible = true
              this.subFormDataDialog = {
                materialCode: this.rowParams.materialCode
              }
            }

          },
          deleteBatch: () => {
            this.$confirm('此操作将删除所选数据, 是否继续?', $i18n.t('common.tip'), {
              confirmButtonText: $i18n.t('common.ok'),
              cancelButtonText: $i18n.t('common.cancel'),
              type: 'warning'
            }).then(() => {
              const ids = data.rows.map((val) => val.id).join(',')
              this.subRowDel(ids)
            })
          },
        }
        fnc[data.handleName]()
      },
      handleSubOperateEventUnit(data) {
        this.title = data.name
        const fnc = {
          add: () => {
            if(this.rowParams.materialCode)
            {
              this.subUnitVisible = true
              this.subUnitFormDataDialog = {
                materialCode: this.rowParams.materialCode
              }
            }
          },
          deleteBatch: () => {
            this.$confirm('此操作将删除所选数据, 是否继续?', $i18n.t('common.tip'), {
              confirmButtonText: $i18n.t('common.ok'),
              cancelButtonText: $i18n.t('common.cancel'),
              type: 'warning'
            }).then(() => {
              const ids = data.rows.map((val) => val.id).join(',')
              this.subRowDelUnit(ids)
            })
          },
        }
        fnc[data.handleName]()
      },
      // 表格行操作事件
      rowOperate({ handleName, name, row }) {
        this.title = name
        const fnc = {
          edit: () => {
            this.formDataDialog = { ...row }
            this.visible = true
          },
          delete: () => {
            this.$confirm('此操作将删除所选数据, 是否继续?', $i18n.t('common.tip'), {
              confirmButtonText: $i18n.t('common.ok'),
              cancelButtonText: $i18n.t('common.cancel'),
              type: 'warning'
            }).then(() => {
              this.rowDel(row.id)
            })
          }
        }
        fnc[handleName]()
      },
      // 表格行操作事件
      subRowOperate({ handleName, name, row }) {
        this.title = name
        const fnc = {
          edit: () => {
            this.subFormDataDialog = { ...row }
            this.subVisible = true
          },
          delete: () => {
            this.$confirm('此操作将删除所选数据, 是否继续?', $i18n.t('common.tip'), {
              confirmButtonText: $i18n.t('common.ok'),
              cancelButtonText: $i18n.t('common.cancel'),
              type: 'warning'
            }).then(() => {
              this.subRowDel(row.id)
            })
          }
        }
        fnc[handleName]()
      },
      subUnitRowOperate({ handleName, name, row }) {
        this.title = name
        const fnc = {
          edit: () => {
            this.subUnitFormDataDialog = { ...row }
            this.subUnitVisible = true
          },
          delete: () => {
            this.$confirm('此操作将删除所选数据, 是否继续?', $i18n.t('common.tip'), {
              confirmButtonText: $i18n.t('common.ok'),
              cancelButtonText: $i18n.t('common.cancel'),
              type: 'warning'
            }).then(() => {
              this.subRowDelUnit(row.id)
            })
          }
        }
        fnc[handleName]()
      },
      doSubmit({ title, api, data }) {
        this.isLoading = true
        api(data)
          .then((res) => {
            const message = res.data.message
            this.$message.success(message || title)
            this.visible = false
            this.refresh()
          })
          .finally(() => {
            this.isLoading = false
          })
      },
      doBrandSubmit({ title, api, data }) {
        this.isSubLoading = true
        api(data)
          .then((res) => {
            const message = res.data.message
            this.$message.success(message || title)
            this.subVisible = false
            this.subRefresh()
          })
          .finally(() => {
            this.isSubLoading = false
          })
      },
      doBrandSubmitUnit({ title, api, data }) {
        this.isSubLoading = true
        api(data)
          .then((res) => {
            const message = res.data.message
            this.$message.success(message || title)
            this.subUnitVisible = false
            this.subUnitRefresh()
          })
          .finally(() => {
            this.isSubLoading = false
          })
      },
      // 弹框提交事件
      handleSubmit(data) {
        if (this.isLoading) return
        const params = this.subFormDataDialog.id
          ? {
            title: $i18n.t('common.editSuccess'),
            api: mesTmMaterialBaseUpdate,
            data
          }
          : {
            title: $i18n.t('common.operateSuccess'),
            api: mesTmMaterialBaseCreate,
            data
          }
        console.log(params)
        this.doSubmit(params)
      },
      // 删除
      rowDel(data) {
        this.loading = true
        mesTmMaterialBaseDeleteById(data)
          .then((res) => {
            const message = res.data.message
            this.$message.success(message || $i18n.t('common.deleteSuccess'))
            this.refresh()
          })
          .finally(() => {
            this.loading = false
          })
      },
      // 弹框提交事件
      subHandleSubmit(data) {
        if (this.isSubLoading) return
        const params = this.subFormDataDialog.id
          ? {
            title: $i18n.t('common.editSuccess'),
            api: mesTmMaterialBrandUpdate,
            data
          }
          : {
            title: $i18n.t('common.addSuccess'),
            api: mesTmMaterialBrandCreate,
            data
          }
        console.log(params)
        this.doBrandSubmit(params)
      },
      subHandleSubmitUnit(data) {
        if (this.isSubLoading) return
        console.info(data)
        const params = this.subUnitFormDataDialog.id
          ? {
            title: $i18n.t('common.editSuccess'),
            api: mesTmMaterialUnitUpdate,
            data
          }
          : {
            title: $i18n.t('common.addSuccess'),
            api: mesTmMaterialUnitCreate,
            data
          }
        console.log(params)
        this.doBrandSubmitUnit(params)
      },
      // 品牌删除
      subRowDel(data) {
        this.loading = true
        mesTmMaterialBrandDeleteById(data)
          .then((res) => {
            const message = res.data.message
            this.$message.success(message || $i18n.t('common.deleteSuccess'))
            this.subRefresh()
          })
          .finally(() => {
            this.loading = false
          })
      },
      subRowDelUnit(data) {
        this.loading = true
        mesTmMaterialUnitDeleteById(data)
          .then((res) => {
            const message = res.data.message
            this.$message.success(message || $i18n.t('common.deleteSuccess'))
            this.subUnitRefresh()
          })
          .finally(() => {
            this.loading = false
          })
      },
      // 刷新主表数据
      refresh(isReset = true) {
        this.$refs.eleTable.getTableData(isReset);
      },
      // 刷新子表
      subRefresh(isReset = true) {
        this.$nextTick(() => {
          this.$refs.domDetailTable.getTableData(isReset)
        })
      },
      subUnitRefresh(isReset = true) {
        this.$nextTick(() => {
          this.$refs.domDetailTableUnit.getTableData(isReset)
        })
      },
      // 子表，请求之前操作
      selfSubBeforeRequest(data) {
        const params = { ...data, ...this.rowParams, ...this.getDetailSearchParams() }
        return params
      },
      // 获取搜索参数
      getDetailSearchParams() {
        let formData = this.$refs.eleDetailFormSearch.formData || {}
        formData = this.getArrtoMap(formData)
        return formData
      },
      // 点击主表行
      masterRowClick(row) {
        this.getSubRequestParams(row)
        this.$refs.domDetailTable.getTableData(true)
        this.$refs.domDetailTableUnit.getTableData(true)
      },
      updateListAfterSubmit() {
        this.$refs.domDetailTable.getTableData(true)
        this.$refs.domDetailTableUnit.getTableData(true)
      },
      // 获取主表点击行参数，用于子表请求参数
      getSubRequestParams(data) {
        console.log(data)
        this.rowParams.materialCode = data.materialCode
        this.subFormDataDialog.materialCode = data.materialCode
        this.subFormDataDialog.materialName = data.materialName
      },
      // inserted() {
      //   const appPage = document.getElementById("appPage");
      //   const isvertical = document.querySelector(
      //     "#scrollbar-main>.is-vertical>.el-scrollbar__thumb"
      //   );
      //   isvertical.style.display = "none";
      //   const _this = this;
      //
      //   let paginationNum = 2;
      //   let otherNum = -60;
      //   //if (paginationNum == 2) otherNum = -60;
      //   appPage.resizeListener = async () => {
      //     const sumHeight =
      //       window.innerHeight -
      //       _this.$refs.tableTop.getBoundingClientRect().top -
      //       90 -
      //       otherNum -
      //       80 * paginationNum; //80为俩表格分页的高度
      //
      //     console.warn(sumHeight)
      //     //this.$refs.domDetailTable.maxHeight= sumHeight /2;
      //     //this.$refs.domDetailTableUnit.maxHeight= sumHeight /2;
      //     _this.maxHeight = sumHeight / 2;
      //   };
      //   addResizeListener(appPage, appPage.resizeListener);
      //
      //   // const sumHeight =
      //   //   window.innerHeight -
      //   //   _this.$refs.tableTop.getBoundingClientRect().top -
      //   //   90 -
      //   //   otherNum -
      //   //   80 * paginationNum; //80为俩表格分页的高度
      //   //
      //   // this.$refs.domDetailTable.maxHeight= sumHeight /2;
      //   // this.$refs.domDetailTableUnit.maxHeight= sumHeight /2;
      // },
    },
    mounted() {
      //this.inserted();
    },
  }
  </script>
  <style lang="scss" scoped>
  .tableLayout {
    display: flex;
    .leftTable {
      border-right: solid 10px #eff2fb;
      box-sizing: border-box;
      padding-right: 10px;
      width: 50%;
    }
    .rightTable {
      padding-left: 10px;
      box-sizing: border-box;
      width: 50%;
    }
  }
  </style>
